package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity2 extends AppCompatActivity implements View.OnFocusChangeListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        EditText phone = findViewById(R.id.et_name);
        phone.addTextChangedListener(new HideTextWatcher(phone, 11));
        EditText password = findViewById(R.id.et_password);
        password.addTextChangedListener(new HideTextWatcher(password, 6));
    }

    @Override
    public void onFocusChange(View view, boolean b) {
        if (view.getId() == R.id.et_password && b) {
            EditText et_phone = findViewById(R.id.et_name);
            String phone = String.valueOf(et_phone.getText());
            if (TextUtils.isEmpty(phone) || phone.length() < 11) {
//                et_phone.requestFocus();
                Toast.makeText(this, "请输入11位手机号", Toast.LENGTH_LONG).show();
            }
        }
    }

    private class HideTextWatcher implements TextWatcher {
        private EditText editText;
        private int mMaxLength;

        public HideTextWatcher(EditText editText, int mMaxLength) {
            super();
            this.editText = editText;
            this.mMaxLength = mMaxLength;
        }

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            String str = editable.toString();
            if ((str.length() == 11 && mMaxLength == 11) || (str.length() == 6 && mMaxLength == 6)) {
                ViewUtil.hideOneInputMethod(MainActivity2.this, editText);
            }
        }
    }
}